package com.wuyou.util;

import cn.hutool.core.util.StrUtil;
import com.wuyou.constant.ExportWordConstant;
import org.apache.poi.xwpf.usermodel.*;

public class ExportWordUtil {

    /**
     * 写入行数据
     * @param document 文档
     * @param text 内容
     */
    public static void writeLine(XWPFDocument document, String textBold, String text, Double size, String color) {
        XWPFParagraph paragraph = document.createParagraph();
        if (StrUtil.isNotEmpty(textBold)) {
            XWPFRun run = paragraph.createRun();
            run.setText(textBold);
            run.setBold(true);
            if (size != null) {
                run.setFontSize(size);
            }
        }
        if (StrUtil.isNotEmpty(text)) {
            XWPFRun run = paragraph.createRun();
            run.setText(text);
            if (size != null) {
                run.setFontSize(size);
            }
            if (StrUtil.isNotEmpty(color)) {
                run.setColor(color);
            }
        }
    }
    public static void writeLine(XWPFDocument document, String textBold, String text, Double size) {
        writeLine(document, textBold, text, size,  null);
    }

    /**
     * 添加表格数据
     * @param dataArray 表格数据
     * @param document 文档
     * @param cellNames 表头
     */
    public static void addTable(String[][] dataArray, XWPFDocument document, String[] cellNames, Boolean[] alignArray) {
        // 创建表格对象
        XWPFTable table = document.createTable(dataArray.length + 1, cellNames.length);

        table.setWidth(ExportWordConstant.TABLE_WIDTH);

        // 添加表格标题行
        XWPFTableRow titleRow = table.getRow(0);
        for (int i = 0; i < cellNames.length; i++) {
            String cellName = cellNames[i];
            XWPFTableCell cell;
            cell = titleRow.getCell(i);
            cell.setText(cellName);
            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            setAlignCenter(cell);
            cell.setColor(ExportWordConstant.TABLE_TITLE_COLOR);
        }
        // 内容
        for (int i = 0; i < dataArray.length; i++) {
            String[] strings = dataArray[i];
            XWPFTableRow dataRow = table.getRow(i + 1);
            for (int j = 0; j < strings.length; j++) {
                XWPFTableCell cell = dataRow.getCell(j);
                if (alignArray[j] != null && alignArray[j]) {
                    cell.setText(strings[j]);
                    setAlignCenter(cell);
                } else {
                    // 一个缩进
                    cell.setText("\n" + strings[j]);
                }
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            }
        }
    }

    private static void setAlignCenter(XWPFTableCell cell) {
        XWPFParagraph paragraph = cell.getParagraphs().get(0);
        paragraph.setAlignment(ParagraphAlignment.CENTER);  // 设置水平居中对齐
    }

}
